//
//  AppDelegate.m
//  WYZ_YoungChat
//
//  Created by dllo on 16/3/11.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "AppDelegate.h"

#import "AppDelegate+EaseMob.h"
#import "AppDelegate+Parse.h"
#import "AppDelegate+UMeng.h"

//会话
#import "ConversationListController.h"

//联系人
#import "ContactListViewController.h"

//抽屉
#import "WYZ_ReSideMenuViewController.h"

#import "RESideMenu.h"
//发现
#import "WYZ_FinderViewController.h"

//必须登录
#import "WYZ_LogInViewController.h"


@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    _connectionState = eEMConnectionConnected;
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 7.0) {
        [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:1.000 green:0.445 blue:0.525 alpha:1.000]];
        [[UINavigationBar appearance] setTitleTextAttributes:
         [NSDictionary dictionaryWithObjectsAndKeys:RGBACOLOR(245, 245, 245, 1), NSForegroundColorAttributeName, [UIFont fontWithName:@ "HelveticaNeue-CondensedBlack" size:21.0], NSFontAttributeName, nil]];
    }

    //铺设左侧登陆抽屉
    WYZ_ReSideMenuViewController *resideMenuVC = [[WYZ_ReSideMenuViewController alloc] init];
    
    self.mainController = [[WYZ_MainViewController alloc] init];
   
    
    //添加到抽屉中
    RESideMenu *sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:_mainController leftMenuViewController:resideMenuVC rightMenuViewController:nil];
    sideMenuViewController.backgroundImage = [UIImage imageNamed:@"login.tiff"];
    sideMenuViewController.menuPreferredStatusBarStyle = 1;
    sideMenuViewController.contentViewShadowColor = [UIColor blackColor];
    sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
    sideMenuViewController.contentViewShadowOpacity = 0.6;
    sideMenuViewController.contentViewShadowRadius = 12;
    sideMenuViewController.contentViewShadowEnabled = YES;
    
    
//    _window.rootViewController = sideMenuViewController;
    
    
    
    //改变状态栏字体颜色为白色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
   
    
    
    
    
    
    
    // 初始化短信验证，appKey和appSecret从后台申请得
    [SMSSDK registerApp:@"fd422f03cd4a" withSecret:@"b66c898540b87435d36f411a1421b8f1"];
    
    
    
#pragma mark 环信注册\
    // 环信UIdemo中有用到Parse，您的项目中不需要添加，可忽略此处。
    [self parseApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    [self easemobApplication:application
didFinishLaunchingWithOptions:launchOptions
                      appkey:@"wang413151868#firstapp"
                apnsCertName:@"binbinnihaohao"
                 otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    
    // 环信UIdemo中有用到友盟统计crash，您的项目中不需要添加，可忽略此处。
    [self setupUMeng];
    
      [self.window makeKeyAndVisible];
    
    [self createJudgeNetWork];
    

    return YES;
}
#pragma mark 判断网络状态(联网)
-(void)createJudgeNetWork{

    Reachability* reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    NSLog(@"--current status: %@", reach.currentReachabilityString);
    //通知监测
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    //block监测
    reach.reachableBlock = ^(Reachability * reachability)
    {
        NSString * netWorkName = [NSString stringWithFormat:@"Baidu Block Says Reachable:%@", reachability.currentReachabilityString];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (reachability.isReachableViaWiFi) {
                
                UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"当前通过WIFI连接" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                [view show];
                NSLog(@"(%@)当前通过wifi连接",netWorkName);
            } else {
                UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"WIFI未开启" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                [view show];
                
                NSLog(@"(%@)wifi未开启，不能用",netWorkName);
            }
            if (reachability.isReachableViaWWAN) {
//                UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"当前通过2g or 3g or 4g连接" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
//                [view show];
                
                NSLog(@"(%@)当前通过2g or 3g or 4g连接",netWorkName);
            } else {
                //                UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"2g or 3g or 4g网络未使用" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                //                [view show];
                
                NSLog(@"(%@)2g or 3g or 4g网络未使用",netWorkName);
            }
        });
    };
    
    reach.unreachableBlock = ^(Reachability * reachability)
    {
        NSString * netWorkName = [NSString stringWithFormat:@"GOOGLE Block Says Reachable(%@)", reachability.currentReachabilityString];
        dispatch_async(dispatch_get_main_queue(), ^{
            //            UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"网络不可用!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
            //            [view show];
            NSLog(@"(%@)网络不可用!",netWorkName);
        });
    };
    
    [reach startNotifier];

    

}
#pragma mark 判断网络状态(不联网)
- (void)reachabilityChanged:(NSNotification*)note {
    Reachability * reach = [note object];
    if(!reach.isReachable) {
        NSLog(@"网络不可用");
        //        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"----网络不可用!" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //        [view show];
        
    }else{
        NSLog(@"网络可用");
    }
    if (reach.isReachableViaWiFi) {
        //        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"当前通过wifi连接" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //        [view show];
        
        NSLog(@"当前通过wifi连接");
    } else {
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"WIFI未开启，不能用" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [view show];
        
        
        NSLog(@"wifi未开启，不能用");
    }
    if (reach.isReachableViaWWAN) {
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"当前通过2g or 3g连接" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        NSLog(@"当前通过2g or 3g连接");
    } else {
        //        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"2g or 3g网络未使用" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //        [view show];
        NSLog(@"2g or 3g网络未使用");
    }
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    //环信进入后台
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
    
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if (_mainController) {
        [_mainController jumpToChatList];
    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    if (_mainController) {
        [_mainController didReceiveLocalNotification:notification];
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.lanou3g.WYZ_YoungChat" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"WYZ_YoungChat" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"WYZ_YoungChat.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
